package com.frxuexi.shop

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.lib_base.entity.ShopBeanItem
import com.frxuexi.lib_base.http.ShopApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext

class ShopDataSource(val apiService: ShopApiService,val type:Int):PagingSource<Int,ShopBeanItem>() {
    override fun getRefreshKey(state: PagingState<Int, ShopBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ShopBeanItem> {
        return withContext(Dispatchers.IO){
            try {
                val page=params.key?:1
                val beanRes = apiService.getShops(type, page).first()
                if(beanRes.code==200){
                    val nextPage=if(page<beanRes.data.totalPage) page+1 else null
                    LoadResult.Page(beanRes.data.list,null,nextPage)
                }else{
                    LoadResult.Error(Exception(beanRes.message))
                }
            }catch (e:Exception){
                LoadResult.Error(Exception(e))
            }
        }
    }
}